package cn.gson.CRM.controller.fund;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.gson.CRM.model.dao.fund.PayPlanDao;
import cn.gson.CRM.model.dao.fund.PayRecordDao;
import cn.gson.CRM.model.entity.PayPlan;
import cn.gson.CRM.model.entity.PayRecord;

@Controller
@RequestMapping("fund/payPlan")
public class PayPlanController {

	@Autowired
	PayPlanDao payPlanDao;
	
	@GetMapping
	public String index(){
		return "fund/payPlan";
	}
	
	@Autowired
	PayRecordDao payRecordDao;
	
	@RequestMapping("list")
	@ResponseBody
	public Map<String, Object> list(PayPlan payPlan,@RequestParam(defaultValue = "1")int page,int rows){
		Map<String, Object> map = new HashMap<>();
		PageRequest pr = new PageRequest(page - 1, rows, Direction.ASC, "id");
		Page<PayPlan> pages = null; 
		if(payPlan.getReturns() != null){
			pages = payPlanDao.findAllByReturnsId(payPlan.getReturns().getReturnId(),pr);
		} else if(payPlan.getPurchase() != null){
			pages = payPlanDao.findAllByPurchaseId(payPlan.getPurchase().getChaseId(),pr);
		} else {
			pages = payPlanDao.findAll(pr);
		}
		map.put("total", pages.getTotalElements());
		map.put("rows", pages.getContent());
		return map;
	}
	
	@PostMapping("save")
	@ResponseBody
	@Transactional
	public JSONObject save(@Valid PayRecord payRecord,BindingResult br){
		JSONObject result = new JSONObject();
		if(br.hasErrors()){
			result.put("err", "保存失败！");
		}else{
			payRecord.setDate(new Date());
			payRecordDao.save(payRecord);
			result.put("success", true);
			
//			payPlanDao.delete(id);
		}
		return result;
	}
	
	
	
	
	
	
	
	
	
}
